<!--反馈详情-->
<template>
  <div class="contain">
    <div class="voice-bigbox">
      <div class="voice-wrap">
        <div class="textbox">
          <x-textarea 
            placeholder="可填写文本信息（最多200字符），试一下语音下单，麻烦注意试听哦..." 
            :rows="2" autosize 
            :max='200'
            :show-counter = false
            v-model="Memo"></x-textarea>
          <div class="voice-btn cf">
            <i class="iconfont icon-video f-l" @click="startvoice"></i>
            <span class="f-l line">|</span>
            <i class="iconfont icon-camera f-l" @click="getFlag()"></i>
          </div>
        </div>
        <ul class="voice-imgbox cf">
          <template  v-for="(item, index) in imgLista">
            <li>
              <img :src="item" @click="previewPic(index)">
              <i class="iconfont icon-del-black" @click="delImg(index)"></i>
            </li>
          </template>
          <!-- <li ><img src="item"><i class="iconfont icon-del-black"></i></li> -->
        </ul>
      </div>
      <div class="voice-mp3-box cf">
        <div class="voice-mp3 cf voiceBox" v-for="(item, index) in Voicelist">
          <div class="vm-ctx f-l" @click="playVoice(item.voice)">
            <span class="txt">点击播放</span>
            <span class="second">{{item.seconds}}'</span>
          </div>
          <span class="vm-del f-l" @click="delVoice(index)">删除</span>
        </div>
      </div>
      <div class="cf">
        <span class="btn-fd f-r" @click="addfeedback()">提交</span>
      </div>
    </div>
    <mt-popup v-model="popupVisible" position="bottom" class="ll-popup" :modal="false">
      <div class="voice-dialog">
        <p class="tit">说出您想要表达的内容</p>
        <p class="tit1">一段录音最长一分钟</p>
        <i class="iconfont icon-video"></i>
        <div class="voice-loading">
          <span></span>
          <span></span>
          <span></span>
          <span></span>
          <span></span>
          <span></span>
          <span></span>
          <span></span>
          <span></span>
          <span></span>
          <span></span>
          <span></span>
          <span></span>
          <span></span>
          <span></span>
        </div>
        <ul class="voice-dialog-btn cf">
          <li @click="closeVoice()">取消</li>
          <li @click="stopvoice()">停止录音</li>
        </ul>
      </div>
    </mt-popup>
    <div class="mask" v-if="popupVisible" @click="closeVoice"></div>
    <template v-if="Feedback.length>0">
      <div class="feedback-tit ft16">全部留言（{{Feedback.length}}）</div>
      <div class="detail-fedbck" v-for="item in Feedback">
        <div>
          <div class="df-head cf">
            <span class="pic f-l"><img src="~images/icon/people-ico.png"></span>
            <span class="f-l">{{item.FeedbackName}}</span>
            <span class="time f-l">{{item.FeedbackTime | timeshort}}</span>
          </div>
          <div class="df-body">
            <p>{{item.Memo}}</p>
            <ul class="pic cf" v-if="item.FeedbackPicture && item.FeedbackPicture != 'null'">
              <template v-for="img in item.FeedbackPicture">
              <li @click="checkImg(img)"><img :src="img | simpleImgUrl"/></li>
              </template>
            </ul>
            <div class="voice-mail cf voiceBox" v-if="item.FeedbackVoice && item.FeedbackVoice.length>0">
              <div class="f-l mr10">语音留言:</div>
              <template v-for="itemvo in item.FeedbackVoice">
              <div class="vm-ctx f-l" @click="playVoice(itemvo.voice)">
                <span class="txt">点击播放</span>
                <span class="second" v-if="itemvo.seconds">{{itemvo.seconds}}'</span>
              </div>
              <!-- <div class="vm-ctx f-l">
                <span class="txt">点击播放</span>
                <span class="second">33'</span>
              </div> -->
              </template>
            </div>
          </div>
        </div>
      </div>
    </template>
    <prev-img :checkimgs ="checkimg" v-on:clearData="checkimg = ''"></prev-img>
    <previewer :list="list" ref="previewer"></previewer>
  </div>
</template>

<script>
import prevImg from "@/components/share/previewPic/preview.vue";
import {Previewer} from 'vux';
export default {
  data() {
    return {
      popupVisible: false,
      Feedback: [],
      Memo: "",
      imgListabase: [],
      imgLista: [],
      list:[],
      Voicelist: [],
      playVoiceId: "",
      checkimg: "",
      times:0,
      clock:'',
      timer:'',

      //APP新增参数
      isApp: false,
      imgLen: 0,
      imgRaw: null,
      recoder: null,
      audioPlayer: null,
      isCancel: false,
      isPlaying: false,
      voiceListBase64: [],
      playingObject: null,
    };
  },
  components: {
    prevImg,
    Previewer
  },
  created() {
    this.plusInit();
    this.getFeedback();
  },
  computed: {
    Guid() {
      return this.$route.query.id;
    },
    BillNo() {
      return this.$route.query.billno;
    }
  },
  watch:{
    //新来的
    imgLista(val){
      var _this = this;
      this.creatList(_this.imgLista)
    },
  },
  mounted() {
    this.$nextTick(function() {});
  },
  beforeDestroy() {
    this.leave();
  },
  methods: {
    plusInit(){
      if (navigator.userAgent.toLowerCase().match(/MicroMessenger/i) != "micromessenger") {
        this.isApp = true;
      }
      if(this.isApp){
        if (window.plus) {
            plusReady();
        } else {
            document.addEventListener('plusready', plusReady, false);
        }
        function plusReady() {
            console.log('plus已经启动并加载...')
        }
      }
    },
    creatList(val){
      this.list = [];
      for(var i = 0;i<val.length;i++){
        var obj = {
          src:val[i]
        }
        this.list.push(obj)
      }
    },
    getFeedback() {
      var self = this;
      var query = {
        Guid: this.Guid
      };
      this.Ajax.post("SearchTRMedPoFeedbacies", query).then(function(resp) {
        if (resp.IsSuccess) {
          self.Feedback = resp.Datas;
          self.Feedback.forEach(function(element, index) {
            self.Feedback[index].FeedbackPicture = JSON.parse(
              element.FeedbackPicture
            );
            self.Feedback[index].FeedbackVoice = JSON.parse(
              element.FeedbackVoice
            );
          }, this);
        }
      });
    },
    addfeedback() {
      var imglist = this.imgListabase,
          voicelist = this.Voicelist;
      if (!imglist && !voicelist && !this.Memo) {
        this.Toast({
          message: "请提交语音或者照片或者文本"
        });
        return false;
      }
      if (imglist.length <= 0 && voicelist.length <= 0 && !this.Memo) {
        this.Toast({
          message: "请提交语音或者照片或者文本"
        });
        return false;
      };
      //缺货反馈判断
      if (this.$route.query.type) {
        this.invoice();
        return false;
      }
      var self = this;
      var userinfo = JSON.parse(localStorage.userinfo);
      
      //测试用，模拟语音数据
      // var localId = {
      //   voice: "wxLocalResource://53432896787455",
      //   seconds: 3
      // }
      // this.Voicelist.push(localId);
      // this.Voicelist.push(localId);

      var query = {
        Guid: this.Guid,
        BillNo: this.BillNo,
        remark: self.Memo,
        FeedbackGUID: userinfo.StaffID,
        FeedbackName: userinfo.Name,
        FeedbackPicture: this.imgListabase,
        FeedbackVoice: JSON.stringify(this.Voicelist),
        FeedbackVoiceBase64: JSON.stringify(this.voiceListBase64)
      };
      this.Ajax.post("CreateTRMedPoFeedback", query).then(function(resp) {
        if (resp.IsSuccess) {
          self.MessageBox.alert("反馈成功").then(action => {
            self.$router.go(-1);
          });
        }
      });
    },

    //---------------------------------------------------------------------语音模块---------------------------------------------------------------------
    //计时器
    counter(){
      var self = this;
      this.times++;
      if(this.isApp){
        if(this.times == 60){
          self.Toast({
            message: "录音时间最长一分钟"
          });
          this.app_stopRecord(self);
        }
      }
    },

    //录音
    startvoice() {
      var self = this;
      if(self.isApp){
        self.app_startRecord(self);
      } else {
        self.wx_startRecord(self);
      }
    },

    //停止录音
    stopvoice() {
      var self = this;
      if(self.isApp){
        self.app_stopRecord(self);
      } else {
        self.wx_stopRecord(self);
      }
    },

    //关闭录音界面
    closeVoice() {
      var self = this;
      if(self.isApp){
        self.app_cancelRecord(self);
      } else {
        self.wx_cancelRecord(self);
      }
    },

    //播放录音
    playVoice(id) {
      var self = this;
      if(self.isApp){
        self.app_playVoice(id, self);
      } else {
        self.wx_playVoice(id, self);
      }
    },

    //离开页面时关闭录音和播放
    leave() {
      var self = this;
      if(self.isApp){
        self.app_leaveFunction(self);
      } else {
        self.wx_leaveFunction(self);
      }
    },

    //删除录音
    delVoice: function(index) {
      var self = this;
      if(self.isApp){
        self.app_delVoice(index, self);
      } else {
        self.wx_delVoice(index, self);
      }
    },

    //===================================微信区域===================================
    //微信调用录音接口
    wx_startRecord: function(){
      var self = this;
      this.popupVisible = true;
      this.jWeixin.startRecord();
      this.times = 0;
      this.clock = setInterval(self.counter, 1000);
      this.jWeixin.onVoiceRecordEnd({
        // 录音时间超过一分钟没有停止的时候会执行 complete 回调
        complete: function(res) {
          var localId = {
                voice: res.localId,
                seconds: 60
              };
          self.Voicelist.push(localId);
          self.popupVisible = false;
          self.Toast({
            message: "录音时间最长一分钟"
          });
        }
      });
    },

    //微信的停止录音
    wx_stopRecord: function(){
      var self = this;
      clearInterval(self.clock);
      this.popupVisible = false;
      this.jWeixin.stopRecord({
        success: function(res) {
          var localId = {
                        voice: res.localId, 
                        seconds: self.times
                      }
          self.Voicelist.push(localId);
        }
      });
    },

    //微信的关闭录音界面
    wx_cancelRecord: function(){
      this.popupVisible = false;
      this.jWeixin.stopRecord();
    },

    //微信播放录音
    wx_playVoice: function(id){
      this.jWeixin.stopRecord();
      var target = $(event.target).parent();
      if(target.hasClass('cur')){
        $(".voiceBox .vm-ctx").removeClass('cur');
      }else{
        var _this = this;
        clearTimeout(_this.timer);
        this.timer = setTimeout(function() {
            $(".voiceBox .vm-ctx").removeClass('cur');
            target.addClass('cur');
            _this.playVoiceId = id;
            _this.jWeixin.playVoice({
              localId: id // 需要播放的音频的本地ID，由stopRecord接口获得
            });
            //监听语音播放完毕接口
            _this.jWeixin.onVoicePlayEnd({
              success: function (res) {
                target.removeClass('cur');
              }
            });
        }, 300);
      };
    },

    //微信离开页面时的操作
    wx_leaveFunction: function(){
      var self = this;
      if (this.playVoiceId) {
        this.jWeixin.stopVoice({
          localId: self.playVoiceId // ID，由stopRecord接口获得
        });
      }
    },

    //微信删除语音
    wx_delVoice: function(index) {
      this.Voicelist.splice(index, 1);
    },
    //===================================微信区域===================================

    //===================================APP区域===================================
    app_startRecord: function(self){
      if(self.audioPlayer){
        self.audioPlayer.stop();
        self.audioPlayer = null;
        self.playingObject = null;
        self.isPlaying = false;
      }
      self.recoder = plus.audio.getRecorder();
      if(!self.recoder){
        plus.nativeUI.toast("获取录音接口失败:" + e.message + "请确认本应用拥有设备权限");
      }
      self.isCancel = false;
      self.popupVisible = true;
      self.times = 0;
      self.clock = setInterval(self.counter, 1000);
      self.recoder.record(
        {
          filename: "_doc/audio/",
          format: "amr"
        },
        function(path) {
          if (self.isCancel == false) {
            plus.io.resolveLocalFileSystemURL(
              path,
              function(entry) {
                self.getAudioFile(path, entry, self.times, self);
              },
              function(e) {
                plus.nativeUI.toast("读取录音文件错误：" + e.message);
              }
            );
          }
        },
        function(e) {
          plus.nativeUI.toast("录音失败:" + e.message);
        }
      );
    },
    //获取语音文件并push进数组
    getAudioFile: function(path, entry, lenTime, Obj) {
      var self = Obj;
      var localId = {
        voice: path,
        seconds: lenTime
      };
      self.Voicelist.push(localId);
      self.Audio2dataURL(path, lenTime);
    },

    //语音文件转换BASE64
    Audio2dataURL: function(path, lenTime) {
      var self = this;
      plus.io.resolveLocalFileSystemURL(path, function(entry){
          entry.file(function(file){
              var reader = new plus.io.FileReader();
              reader.readAsDataURL(file);
              reader.onloadend = function (e) {
                var amr = e.target.result;
                    amr = amr.substring((amr.indexOf('base64,') + 7), amr.length)
                var audioBase64Item = {
                      "voice": amr,
                      "seconds":lenTime
                }
                self.voiceListBase64.push(audioBase64Item);
            };
          },
          function(e) {
            plus.nativeUI.toast("读写出现异常: " + e.message);
          }
        );
      });
    },

    //APP停止录音
    app_stopRecord: function(self){
      clearInterval(self.clock);
      this.recoder.stop();
      this.popupVisible = false;
    },

    //APP关闭录音界面
    app_cancelRecord: function(self){
      clearInterval(self.clock);
      this.isCancel = true;
      this.recoder.stop();
      this.popupVisible = false;
    },

    //APP播放录音
    app_playVoice: function(id, self){
      var target = $(event.target).parent();
      if(id.indexOf('wxLocalResource') > -1){
        plus.nativeUI.toast('此语音为微信端发布，请登录微信试听');
      } else {
        if(id.indexOf('/File/Index/') > -1){
          var id = 'https://image.csyaoly.com' + id;
        }
        if(self.playingObject == id){ //相同文件点击切换播放/停止
          $(".voiceBox .vm-ctx").removeClass('cur');
          self.audioPlayer.stop();
          self.audioPlayer = null;
          self.playingObject = null;
          self.isPlaying = false;
        } else {
          GoPlay(self, target);
        }
      }
      
      //播放
      function GoPlay(self, target){
        if(self.isPlaying == false) {
          self.audioPlayer = plus.audio.createPlayer(id);
          self.isPlaying = true; //正在播放
          self.playingObject = id; //正在播放的对象
          $(".voiceBox .vm-ctx").removeClass('cur');
          target.addClass('cur');
          self.audioPlayer.play(
            function() {
              $(".voiceBox .vm-ctx").removeClass('cur');
              self.playingObject = null; //正在播放的对象
              self.audioPlayer = null; //清空
              self.isPlaying = false; //播放完成事件
            },
            function(e) {
              plus.nativeUI.toast("播放器错误:" + e.message);
            }
          );
        } else {
          $(".voiceBox .vm-ctx").removeClass('cur');
          self.audioPlayer.stop(); //停止
          self.isPlaying = false; //正在播放
          self.playingObject = null;
          self.audioPlayer = null; //清空
          self.audioPlayer = plus.audio.createPlayer(id); //重新注册播放
          self.isPlaying = true;
          self.playingObject = id;
          $(".voiceBox .vm-ctx").removeClass('cur');
          target.addClass('cur');
          self.audioPlayer.play(
            function() {
              $(".voiceBox .vm-ctx").removeClass('cur');
              self.playingObject = null; //正在播放的对象
              self.audioPlayer = null; //清空
              self.isPlaying = false; //播放完成
            },
            function(e) {
              plus.nativeUI.toast("播放器错误:" + e.message);
            }
          );
        }
      }
    },

    //APP离开页面时的操作，停止+清除（播放器+录音器）
    app_leaveFunction:  function(self){
      self.isCancel = true;
      if(self.audioPlayer){
        self.audioPlayer.stop();
        self.audioPlayer = null;
      }
      if(self.recoder){
        self.recoder.stop();
        self.recoder = null;
      }
    },

    //APP删除语音，如果删除的是正在播放的则停止和清空播放器
    app_delVoice: function(index, self){
      if(self.playingObject == self.Voicelist[index].voice){
        self.audioPlayer.stop();
        self.audioPlayer = null;
        self.playingObject = null;
        self.isPlaying = false;
      }
      this.Voicelist.splice(index, 1);
    },
    
    //===================================APP区域===================================

    //---------------------------------------------------------------------语音模块---------------------------------------------------------------------

    //---------------------------------------------------------------------图片模块---------------------------------------------------------------------
    //图片模块功能入口
    getFlag: function() {
      var self = this;
      if(self.isApp){
        self.app_uploadImg(self);
      } else {
        self.wx_uploadImg(self);
      }
    },
    
    //===================================微信区域===================================
    //微信调用选择图片
    wx_uploadImg: function(self){
      let currentSize = this.imgLista.length;
      self.jWeixin.chooseImage({
        count: 9, // 默认9
        sizeType: ["compressed"], // 可以指定是原图还是压缩图，默认二者都有
        sourceType: ["album", "camera"], // 可以指定来源是相册还是相机，默认二者都有
        success: function(res) {
          var localIds = res.localIds; // 返回选定照片的本地ID列表，localId可以作为img标签的src属性显示图片
          if (self.imgLista.length + localIds.length > 9) {
            self.Toast({
              message: "最多上传9张图片."
            });
            return false;
          }
          localIds.forEach(li => {
            self.imgLista.push(li);
          });
          self.wx_getLocalImgDataC(currentSize);
        }
      });
    },

    //选择本地图片
    wx_getLocalImgDataC: function(index) {
      var self = this;
      this.jWeixin.getLocalImgData({
        localId: self.imgLista[index], // 图片的localID
        success: function(res) {
          let localData = res.localData;
           if (window.__wxjs_is_wkwebview) {
            //  var imgbase64 = localData.substr(22,localData.length);
            var imgbase64 = localData.substring((localData.indexOf('base64,') + 7), localData.length)
            self.imgLista.splice(index, 1, localData);
            self.imgListabase.push(imgbase64);
          } else {
            self.imgListabase.push(localData);
          }
          self.getLocalImgDataC(index + 1);
        }
      });
    },
    //===================================微信区域===================================

    //===================================APP区域===================================
    //调用NativeUI
    app_uploadImg: function(self){
      self.imgLen = self.imgLista.length;
      if(self.imgLen >= 9){
        plus.nativeUI.toast('最多只能选择9张图片');
      } else {
        var actionbuttons = [{ title: "拍照" }, { title: "相册选取" }];
        var actionstyle = { title: "选择照片", cancel: "取消", buttons: actionbuttons };
        plus.nativeUI.actionSheet(actionstyle, function(e) {
            if (e.index == 1) {
                self.pickCamera(self);
            } else if (e.index == 2) {
                self.pickGallery(self);
            }
        });
      }
    },
    //APP调用摄像头
    pickCamera: function(self) {
      var cmr = plus.camera.getCamera();
      cmr.captureImage(function(p) {
          plus.io.resolveLocalFileSystemURL(p, function(entry) {
            var jsonStr = '{"files":["'+ entry.toLocalURL() +'"]}'
            self.imgRaw = JSON.parse(jsonStr);
            self.compressImage(0);
          }, function(e) {
              plus.nativeUI.toast("读取拍照文件错误：" + e.message);
          });
      }, function(e) {
      }, {
          filename: "_doc/camera/",
          index: 1
      });
    },
    //APP调用相册
    pickGallery: function(self) {
      plus.gallery.pick(function(e){
        self.imgRaw = e;
        self.compressImage(0);
      },function (e) {
        console.log("取消选择图片");
      },{
        filter:"image",
        multiple:true,
        maximum:(9 - self.imgLen),
        system:false,
        onmaxed:function(){
        plus.nativeUI.alert('最多只能选择9张图片');
        }
      },{
        filter: "image",
        multiple: true,
        system: false
      });
    },
    //压缩选取的图片
    compressImage: function(num) {
      var self = this;
      var e = this.imgRaw;
      if(!e.files[num]){
        this.imgRaw = null;
      } else {
        var ext = e.files[num].substr(e.files[num].lastIndexOf("."), e.files[num].length);
        var filename = (new Date()).valueOf().toString() + ext;
        var compName = "_doc/compressed/" + filename;
        var path = e.files[num];
        plus.zip.compressImage({
            src: path,//src: (String 类型 )压缩转换原始图片的路径  
            dst: compName,//压缩转换目标图片的路径  
            quality: 50,//quality: (Number 类型 )压缩图片的质量.取值范围为1-100  
            overwrite: true,//overwrite: (Boolean 类型 )覆盖生成新文件  
            format: 'jpg',
        },
        function(event) {
          var fileReader = new plus.io.FileReader();
          fileReader.readAsDataURL(event.target);
          fileReader.onloadend = function(s) {
                if (self.imgLista.length > 9) {
                  plus.nativeUI.toast("最多上传9张图片");
                  return;
              } else {
                  var picUrl = s.target.result.toString();
                  var dataimg = picUrl.split(',');
                  self.imgLista.push(picUrl);
                  self.imgListabase.push(dataimg[1]);
                  self.compressImage(num + 1);
              }
          }
        }, function(error) {
            plus.nativeUI.toast("压缩图片失败，请稍候再试");
        });
      }
    },
    //===================================APP区域===================================

    //预览图片
    previewPic: function(index) {
      this.$refs.previewer.show(index);
    },
    //删除图片
    delImg: function(index) {
      this.imgLista.splice(index, 1);
      this.imgListabase.splice(index, 1);
    },
    //---------------------------------------------------------------------图片模块---------------------------------------------------------------------

    
    //缺货提交
    invoice() {
      var self = this;
      var userinfo = JSON.parse(localStorage.userinfo);
      var query = {
        Guid: this.Guid,
        BuyerGUID: userinfo.StaffID,
        BuyerName: userinfo.Name,
        BillState: "P11",
        type: "",
        FeedbackGUID: userinfo.StaffID,
        FeedbackName: userinfo.Name
      };
      this.Ajax.post("OrderAcceptance", query).then(function(resp) {
        if (resp.IsSuccess) {
          self.MessageBox.alert("缺货反馈成功").then(action => {
            self.$router.push({
              path: "/order/erpList"
            });
          });
        } else {
          self.Toast({
            message: resp.ErrorMessage || "操作失败，请稍后重试"
          });
        }
      });
    },
    checkImg(value) {
      this.checkimg = value;
    }
  }
};
</script>